package cn.lisens.monitor.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import io.micrometer.core.annotation.Timed;

@Controller
public class MonitorController {
	
	public static Integer userId = 0;

//	@Timed(value = "MonitorController_index", description = "首页描述", histogram = true)
	@RequestMapping("index")
	@ResponseBody
	public String index() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "test";
	}
	
	@RequestMapping("/login")
	@ResponseBody
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        System.err.println(session.getId());
        userId++;
        session.setAttribute("userId", "user"+userId);
        return "success";
    }
	
	@GetMapping("/oom")
	@ResponseBody
	public String controlledOOM(@RequestParam(defaultValue = "100") int mb) {
	    try {
	        List<byte[]> list = new ArrayList<>();
	        for (int i = 0; i < mb; i++) {
	            // 每次分配1MB的内存
	            list.add(new byte[1024 * 1024]);
	            Thread.sleep(100); // 减慢溢出速度
	        }
	    } catch (InterruptedException e) {
	        Thread.currentThread().interrupt();
	    }
	    return "Allocated " + mb + " MB";
	}
}
